#!/bin/bash

busybox devmem 0x43cc0000 w 500000
busybox devmem 0x43cc0004 w 1

while true
  do
    if [ "$(busybox devmem 0x41210000)" = 0x00000001 ]; then
      # stop dma and useless services
      systemctl stop rcs-dma.service
      sudo pkill -SIGKILL radius_control_software_dma_server

#      # TODO serial_number
#      alarm=$(jq -n \
#          --arg code 108 \
#          --arg value 1 \
#          --arg state "true" \
#          --arg time "$(date '+%Y-%m-%d %H:%M:%S')" \
#          --arg serial_number "TO_DO" \
#          '$ARGS.named'
#      )
#
#      curl -X 'POST' \
#      "http:/localhost:5000/server_integration/log_alarm" \
#      -H 'Accept:application/json' \
#      -H 'Content-Type:application/json' \
#      d "$alarm"


      #get config
      CONFIG=$( \
          curl -X 'GET' \
          "http:/localhost:5000/server_integration/get-full-unit-configuration" \
          -H 'Accept:application/json' \
          | python -c "import sys, json; print(json.load(sys.stdin)['unit_configuration']['server'])")

      IP=$( echo $CONFIG | sed "s/'/\"/g" | python -c "import sys, json; print(json.load(sys.stdin)['ip'])")
      PORT=$( echo $CONFIG | sed "s/'/\"/g" | python -c "import sys, json; print(json.load(sys.stdin)['port'])")


      #stop other
      systemctl stop rcs-server-integration.service
      systemctl stop rcs-main.service
      sudo pkill -SIGKILL python
      sudo pkill -SIGKILL redis
      busybox devmem 0x41200000 w 0x0
      busybox devmem 0x43C00000 w 0x0

      echo 0 > /sys/class/fclkcfg/fpga-clk0/enable
      echo 0 > /sys/class/fclkcfg/fpga-clk1/enable
      #echo ondemand > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor
      echo 333334 > /sys/devices/system/cpu/cpufreq/policy0/scaling_setspeed
      busybox devmem 0x41220000 w 0


      #post to server
#      while true
#      do
#      curl -X 'POST' \
#          "http:/$IP:$PORT/api/set_alarm/" \
#          -H 'Accept:application/json' \
#          -H 'Content-Type:application/json' \
#          -d "$alarm"
#          sleep 1
#      done
      sleep 0.1
    fi

    sleep 0.1
done
